package org.smartopen.unionpay.openapi.interceptor;

import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.smartframework.common.encrypt.RsaUtil;
import org.smartframework.core.util.Charsets;
import org.smartopen.unionpay.openapi.component.UnionPayOpenApiProperties;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 拦截Fegin的get请求，使之支持get请求pojo传参
 */
@Slf4j
@RequiredArgsConstructor
public class UnionPayOpenApiRequestInterceptor implements RequestInterceptor {


    private final UnionPayOpenApiProperties properties;

    @Override
    public void apply(RequestTemplate template) {
        template.header("unionpay-source", "smart-unionpay");

        //是否进行签名
        if (StrUtil.isNotEmpty(properties.getPrivateKey())) {
            String nonceStr = StrUtil.uuid().replace("-", "");
            String timestamp = System.currentTimeMillis() / 1000 + "";
            template.header("unionpay-noncestr", nonceStr);
            template.header("unionpay-timestamp", timestamp);
            template.header("unionpay-sign", getSign(nonceStr, timestamp, template, properties.getPrivateKey()));
        }

    }

    private String getSign(String nonceStr, String timestamp, RequestTemplate template, String priKey) {
        String signContent = Arrays.asList(nonceStr, timestamp, template.path(), nonceStr, template.bodyTemplate()).stream().collect(Collectors.joining("\n"));
        return RsaUtil.encryptByPrivateKeyToBase64(priKey, signContent.getBytes(Charsets.UTF_8));
    }

}